#define _GNU_SOURCE
#include "daemon_runner.h"
#include "daemon_sub_process.h"
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>

static SubProcess *sub_processes[SUB_PROCESS_COUNT];
static char *cmd_params[SUB_PROCESS_COUNT] = {"app", "ota"};

int is_running = 1;
static void exit_handler(int sig) {
    is_running = 0;
}

int daemon_runner_run()
{
    // 将当前进程设置为守护进程（后台进程）
    daemon(0, 1);
    // 输入输出重定向
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    open("/dev/null", O_RDWR); // fd = 0  STDIN_FILENO
    open(LOG_FILE_PATH, O_CREAT|O_WRONLY|O_APPEND, 0644); // fd = 1  STDOUT_FILENO
    open(LOG_FILE_PATH, O_CREAT|O_WRONLY|O_APPEND, 0644); // fd = 2  STDERR_FILENO

    signal(SIGINT, exit_handler);  // ctrl+C
    signal(SIGTERM, exit_handler); // kill

    // 创建所有子进程的结构体对象
    for (int i = 0; i < SUB_PROCESS_COUNT; i++) {
        sub_processes[i] = daemon_sub_process_init(cmd_params[i]);
    }

    // 每隔1秒检查一次所有子进程的启动
    while(is_running) {
        for (int i = 0; i < SUB_PROCESS_COUNT; i++) {
            daemon_sub_process_checkStart(sub_processes[i]);
        }
        sleep(1);
    }

    // 在守护进程退出前，关闭所有子进程
    for (int i = 0; i < SUB_PROCESS_COUNT; i++) {
        daemon_sub_process_stop(sub_processes[i]);
    }

    return 0;
}